package com.easy.life.controller;


import com.easy.life.common.R;
import com.easy.life.redis.impl.StringRedisServiceImpl;
import com.easy.life.service.SendSms;
import com.easy.life.service.UserService;
import com.easy.life.utils.NumberRandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
public class SendSmsController {
    @Autowired
    private SendSms sendSms;
    @Autowired
    private StringRedisServiceImpl stringRedisService;
    @Autowired
    private UserService userService;

    @GetMapping("/send")
    public R getCode(@RequestParam String phone){
        Boolean isPhone = userService.isPhone(phone);
        if (isPhone){
            return R.error(402,"该手机号已经被注册了");
        }

        String code = (String) stringRedisService.get(phone);
        if (!StringUtils.isEmpty(code)){
            return R.error(401,"验证码已发送,还未过期");
        }

        code= NumberRandomUtil.randomNumBuilder();
        //HashMap<String,Object> param=new HashMap<>();
       // param.put("code",code);

        boolean isSend =sendSms.sendByThree(phone,code);
        if (isSend){
            stringRedisService.set(phone,code,300);
            return R.ok("发送成功");
        }else {
           return R.error(404,"发送失败");
        }
    }
}
